<?php
namespace App\Api\Controllers\User;


use Aliyun\AliSms;
use App\Api\Controllers\BaseController;
use App\Api\Controllers\Rsa\RsaE;
use App\Models\Order;
use App\Models\Permission;
use App\Models\Role;
use App\Models\SmsConfig;
use App\Models\ServerRate;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\User;
use App\Models\UserDayOrder;
use App\Models\UserMonthOrder;
use App\Models\UserRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class UserController extends BaseController
{
    //app 首页的统计
    public function get_my_data(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;
            //总下级数量
            $sub_user_count = count($this->getSubIds($user_id, false));
            //总门店数 含下级
            $store_count = Store::whereIn('user_id', $this->getSubIds($user_id, true))->select('id')->count('id');

            //今日
            //总下级数量

            $beginToday = date("Y-m-d 00:00:00", time());
            $endToday = date("Y-m-d H:i:s", time());

            $sub_user_count1 = count($this->getSubIds($user_id, false, $beginToday, $endToday));
            //总门店数 含下级
            $store_count1 = Store::whereIn('user_id', $this->getSubIds($user_id, true, $beginToday, $endToday))->select('id')->count('id');

            //昨日
            //总下级数量
            $beginYesterday = date("Y-m-d 00:00:00", strtotime("-1 day"));
            $endYesterday = date("Y-m-d 23:59:59", strtotime("-1 day"));

            $sub_user_count2 = count($this->getSubIds($user_id, false, $beginYesterday, $endYesterday));
            //总门店数 含下级
            $store_count2 = Store::whereIn('user_id', $this->getSubIds($user_id, true, $beginYesterday, $endYesterday))->select('id')->count('id');


            $new_store_count = $store_count2 - $store_count1;
            $new_sub_user_count = $sub_user_count2 - $sub_user_count1;


            //今日流水
            $day = date('Ymd', time());
            $day_order = UserDayOrder::whereIn('user_id', $this->getSubIds($user_id))
                ->where('day', $day)
                ->select('total_amount')
                ->sum('total_amount');

            //昨日流水
            $old_day = date("Ymd", time() - 24 * 60 * 60);
            $day = date('Ymd', time());
            $old_day_order = UserDayOrder::whereIn('user_id', $this->getSubIds($user_id))
                ->where('day', $old_day)
                ->select('total_amount')
                ->sum('total_amount');

            //月流水
            $month = date('Ym', time());
            $month_order = UserMonthOrder::whereIn('user_id', $this->getSubIds($user_id))
                ->where('month', $month)
                ->select('total_amount')
                ->sum('total_amount');

            //待进件数量
            $incoming_parts_count = Store::whereIn('user_id', $this->getSubIds($user_id, true))
                ->where('status', '=', '2')
                ->where('pid', '=', '0')
                ->where('is_delete', '=', '0')
                ->where('is_close', '=', '0')
                ->count('id');
            //已进件数量
            $in_audit_count = Store::whereIn('user_id', $this->getSubIds($user_id, true))
                ->where('status', '=', '1')
                ->where('pid', '=', '0')
                ->where('is_delete', '=', '0')
                ->where('is_close', '=', '0')
                ->count('id');
            //驳回数量
            $reject_count = Store::whereIn('user_id', $this->getSubIds($user_id, true))
                ->where('status', '=', '3')
                ->where('pid', '=', '0')
                ->where('is_delete', '=', '0')
                ->where('is_close', '=', '0')
                ->count('id');

            return json_encode([
                'status' => 1,
                'message' => '数据请求成功',
                'data' => [
                    'sub_user_count' => '' . $sub_user_count . '',
                    'store_count' => '' . $store_count . '',
                    'new_store_count' => '' . $new_store_count . '',
                    'new_sub_user_count' => '' . $new_sub_user_count . '',
                    'day_order' => '' . $day_order . '',
                    'old_day_order' => '' . $old_day_order . '',
                    'month_order' => '' . $month_order . '',
                    'incoming_count' => '' . $incoming_parts_count . '',
                    'in_audit_count' => '' . $in_audit_count . '',
                    'reject_count' => '' . $reject_count . '',
                ]
            ]);


        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }
    
    
    public function server_log(Request $request){
        try {
            $token = $this->parseToken();
            $user_id=$token->user_id;
            $user_ids = $this->getSubIds($user_id); // 所有下级代理
            
            $date_time=date("Y-m-d",strtotime("-1 day"));
            
            $where = [];
            $where[] = ['pid', '=', 0];
            $where[] = ['is_delete', '=', 0];
            $where[] = ['is_close', '=', 0];
            
            
            $obj = DB::table('stores');
            $stores = $obj->where($where)->whereIn('user_id', $user_ids)->orderBy('created_at', 'desc')->select('store_name','store_id')->get();
            $stores=json_decode($stores,true);
            
            foreach ($stores as $k=>$v){
                $server_day_log= DB::table('service_day_money')->where('store_id',$v['store_id'])->where('settling_day',$date_time)->first();
                if(empty($server_day_log)){
                    $stores[$k]['order_count']='0.00';
                    $stores[$k]['settling_day']=$date_time;
                    $stores[$k]['count']='0.00';
                }else{
                    $stores[$k]['order_count']=$server_day_log->order_count;
                    $stores[$k]['settling_day']=$date_time;
                    $stores[$k]['count']=$server_day_log->count;
                }
            }
            return json_encode([
                'status' => '1',
                'data' => $stores
            ]);
        } catch (\Exception $ex) {
            $this->status = -1;
            $this->message = $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine();
            return $this->format();
        }
    }
    
        /**
     * 门店列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store_lists(Request $request){
        try {
            $token = $this->parseToken();
            $user_id=$token->user_id;
            $user_ids = $this->getSubIds($user_id); //所有下级代理

            $obj = DB::table('stores');
            $where = [];
            $where[] = ['is_delete', '=', 0];
            $where[] = ['is_close', '=', 0];

            $obj->where($where)->whereIn('user_id', $user_ids)->where('pid', 0);
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('id', 'asc')->get();

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }
    
    public function custom_query(Request $request){
        try{
            $token = $this->parseToken();
            $user_id=$token->user_id;
            $user_ids = $this->getSubIds($user_id); //所有下级代理
            
            $store_id = $request->get('store_id', '');
            $time_start = $request->get( 'time_start', date('Y-m-d', time()) ); // 开始时间
            $time_end = $request->get( 'time_end', date('Y-m-d', time()) ); // 结束时间
            // 限制时间
            $date = ( strtotime($time_end) - strtotime($time_start) ) / 86400;
            $day = 31;
            if($date > $day){
                return json_encode([
                    'status' => 2,
                    'message' => '时间跨度不能超过'.$day.'天'
                ]);
            }

            if ($time_start) {
                $time_start = date('Y-m-d', strtotime($time_start));
                $where1[] = ['settling_day', '>=', $time_start];
            }

            if ($time_end) {
                $time_end = date('Y-m-d', strtotime($time_end));
                $where1[] = ['settling_day', '<=', $time_end];
            }
            $where = [];
            $where[] = ['pid', '=', 0];
            $where[] = ['is_delete', '=', 0];
            $where[] = ['is_close', '=', 0];
            
            
            $obj = DB::table('stores');
            $stores = $obj->where($where)->whereIn('user_id', $user_ids)->orderBy('created_at', 'desc')->select('store_name','store_id')->get();
            $stores=json_decode($stores,true);
            foreach($stores as $k=>$v){
                $server_day_log= DB::table('service_day_money')->where('store_id','202210138555581688')->where($where1)->first();
                if(empty($server_day_log)){
                    $stores[$k]['order_count']='0.00';
                    $stores[$k]['settling_day']=$time_start.'-'.$time_end;
                    $stores[$k]['count']='0.00';
                }else{
                    $order_count= DB::table('service_day_money')->where('store_id',$v['store_id'])->where($where1)->sum('order_count');
                    $count= DB::table('service_day_money')->where('store_id',$v['store_id'])->where($where1)->sum('count');;
                    $stores[$k]['order_count']=$order_count;
                    $stores[$k]['settling_day']=$time_start.'-'.$time_end;
                    $stores[$k]['count']=$count;
                }
            }

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($stores);

        }catch(\Exception $exception){
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }
    
    


    public function get_sub_users(Request $request)
    {
        try {
            $token = $this->parseToken();
            $login_user_id = $token->user_id;
            $user_id = $request->get('user_id', $login_user_id);
            $self = $request->get('self', false);
            $User_id_s = $this->getSubIds($user_id, $self); //不含自己
            $return_type = $request->get('return_type', '');
            $user_name = $request->get('user_name', '');
            $sub_type = $request->get('sub_type', '');
            $level = $request->get('level', '');
            $Display = $request->get('display', ''); //是否全部显示手机号

            $where = [];
            $where[] = ['is_delete', '=', 0];
            if ($user_name) {
                $where[] = ['name', 'like', '%' . $user_name . '%'];
            } else {
                if ($level) {
                    $where[] = ['level', '=', $level];
                }
            }

            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("users");
            } else {
                $obj = DB::table('users');
            }

            if ($sub_type == "1") {
                $where[] = ['level', '<', '2'];
            }

            if ($return_type == "layui") {
                $Users = User::where('id', $login_user_id)
                    ->where($where)
                    ->with('children')
                    ->select('id', 'pid', 'money', 'name', 'phone', 'level', 's_code', 'logo', 'settlement_money')
//                    ->select('id', 'pid', 'money', 'name', 'phone', 'level', 's_code', 'logo', 'profit_ratio', 'sub_profit_ratio')
                    ->get()->toArray();

                if (!$Display) {
                    array_walk_recursive($Users, function(&$values, $keys){
                        if ($keys == 'phone') {
                            $values = substr($values, 0, 3).'****'.substr($values, 7); //手机号加盐
                        }

                        return $values;
                    });
                }

                return json_encode([
                    'status' => '1',
                    'data' => $Users
                ]);
            }

            $obj = $obj->where($where)
                ->whereIn('id', $User_id_s);
//            $this->t = $obj->count();
//            $data = $this->page($obj)->get();
//            $this->status = 1;
//            $this->message = '数据返回成功';
//            return $this->format($data);
            $data = $obj->get();
            return json_encode([
                'status' => 1,
                'message' => '数据返回成功',
                'data' => $data
            ]);
        } catch (\Exception $ex) {
            $this->status = -1;
            $this->message = $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine();
            return $this->format();
        }
    }


    /**
     * 跨数据库-获取首付科技-用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function get_sf_sub_users(Request $request)
    {
        try {
            $token = $this->parseToken();
            $user_name = $request->get('user_name', '');
            $login_user_id = $token->user_id;

            $user_info = User::where('id', $login_user_id)
                ->where('is_delete', '=', 0)
                ->first();
            if (!$user_info) {
                $this->status = '2';
                $this->message ='当前用户状态异常或用户不存在';
                return $this->format();
            }

            $where = [];
            if ($user_name) {
                $where[] = ['name', 'like', '%' . $user_name . '%'];
            }

            if (env('DB_DATABASE_FIRSTPAY')) {
                $db = DB::connection("mysql_firstpay");
            } else {
                $this->status = '3';
                $this->message = '首付科技数据连接异常';
                return $this->format();
            }

            $obj = $db->table("users")
                ->where($where)
                ->where('is_delete', '=', 0);
            $this->t = $obj->count();
            $data = $this->page($obj)->get();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();

            return $this->format();
        }

        $this->status = '1';
        $this->message = '数据返回成功';
        return $this->format($data);
    }


    public function get_del_sub_users(Request $request)
    {
        try {
            $user = $this->parseToken();
            $login_user_id = $user->user_id;
            $user_id = $request->get('user_id', $login_user_id);
            $self = $request->get('self', false);
            $User_id_s = $this->getSubIds($user_id, $self);//不含自己

            $where = [];
            $where[] = ['is_delete', '=', 1];


            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("users");
            } else {
                $obj = DB::table('users');
            }

            $obj = $obj->where($where)
                ->whereIn('id', $User_id_s);
            $this->t = $obj->count();
            $data = $this->page($obj)
                ->orderBy('updated_at', 'desc')
                ->get();

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();

            return $this->format();

        }

    }


    //添加代理商或者业务员
    public function add_sub_user(Request $request)
    {
        try {
            $token = $this->parseToken();
            $login_user_id = $token->user_id;
            $phone = $request->get('phone');
            $password = $request->get('password');
            $name = $request->get('user_name'); //公司名称
            $people = $request->get('people', ''); //联系人姓名
            $user_id = $request->get('user_id', '');  //上级代理id
            $user_id = isset($user_id) ? $user_id : $token->user_id;
            $province_name = $request->get('province_name', '全国');
            $city_name = $request->get('city_name', '全国');
            $area_name = $request->get('area_name', '全国');
            $address = $request->get('address', '全国');
            $p_id = $request->get('pid', '');  //上级id

            if ($p_id) {
                $pid_user = User::where('id', $p_id)
                    ->where('is_delete', '0')
                    ->first();
                if (!$pid_user) {
                    return json_encode([
                        'status'=>'2',
                        'message'=>'上级代理不存在或状态异常'
                    ]);
                }
            }

            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }

            $login_user = User::where('id', $login_user_id)->first();

            $hasPermission = $login_user->hasPermissionTo('添加下级代理');
            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '暂不支持添加下级代理']);
            }

            //4级以后如果没有开权限就不能在开了
            if ($user->level >= 4) {
                return json_encode([
                    'status' => 2,
                    'message' => '暂不支持开下级账户(三级代理已超)'
                ]);
            }
            $s_code = rand(1000, 9999);
            $check_data = [
                'phone' => '手机号',
                'password' => '密码',
                'user_name' => '公司名字',
//                'people' => '联系人姓名'
            ];

            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            //验证手机号
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $phone)) {
                return json_encode([
                    'status' => 0,
                    'message' => '手机号码不正确'
                ]);
            }

            $data = $request->all();
            $rules = [
                'phone' => 'required|min:11|max:11|unique:users',
            ];
            $validator = Validator::make($data, $rules);
            if ($validator->fails()) {
                return json_encode([
                    'status' => 2,
                    'message' => '账号已注册请直接登录'
                ]);
            }

            $rules = [
                's_code' => 'required|min:4|max:4|unique:users',
            ];
            $validator = Validator::make(['s_code' => $s_code], $rules);
            if ($validator->fails()) {
                return json_encode([
                    'status' => 2,
                    'message' => '激活码生成失败，请重新提交资料'
                ]);
            }

            //验证密码
            if (strlen($password) < 6) {
                return json_encode([
                    'status' => 2,
                    'message' => '密码长度不符合要求'
                ]);
            }

            $level = $user->level + 1;
            $level_name = "业务员";
            $role_name = "业务员";

            if ($level == 1) {
                $level_name = "服务商";
                $role_name="服务商";
            }
            if ($level == 2) {
                $level_name = "代理商";
                $role_name = "代理商";
            }
            if ($p_id) {
                $dataIn['pid'] = $pid_user->id;
                $dataIn['pid_name'] = $pid_user->name;
            } else {
                $dataIn['pid'] = $user->id;
                $dataIn['pid_name'] = $user->name;
            }
//            $level_name=$request->get('level_name',$level_name); //展示名称
            $dataIn['config_id'] = $user->config_id;
            $dataIn['email'] = $phone . '@139.com';
//            $dataIn['pid'] = $pid_user->id;
//            $dataIn['pid_name'] = $pid_user->name;
            $dataIn['level'] = $level;
            $dataIn['level_name'] = $level_name;
            $dataIn['logo'] = $people;  //联系人姓名
            $dataIn['password'] = bcrypt($password);
            $dataIn['name'] = $name;
            $dataIn['phone'] = $phone;
            $dataIn['s_code'] = $s_code;
            $dataIn['province_name'] = $province_name;
            $dataIn['city_name'] = $city_name;
            $dataIn['area_name'] = $area_name;
            $dataIn['address'] = $address;
            $dataIn['s_code_url'] = url('/api/user/s_code_url?s_code=' . $s_code);
            $dataIn['sub_code_url'] = url('/api/user/sub_code_url?s_code=' . $s_code);

            //超级服务商
            if ($user->pid == 0) {
                $dataIn['config_id'] = $phone;
                $dataIn['level'] = 1;
            }

            $User = User::create($dataIn);

            //自动分配权限
            try {
                $user_id = $User->id;
                $user = User::where('id', $user_id)->first();
                $Permission = Role::where('display_name', $role_name)->first();
                if ($Permission) {
                    $user->assignRole($Permission->id);
                }
            } catch (\Exception $ex) {
                Log::info('添加代理商-错误');
                Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
                return json_encode([
                    'status' => -1,
                    'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
                ]);
            }

            //添加成功后，发送短信通知
            if ($User && $phone) {
                $config_id = $user->config_id;

                //发送"合伙人通知"短信息通知
                $config = SmsConfig::where('type', '12')
                    ->where('config_id', $config_id)
                    ->first();
                if (!$config) {
                    $config = SmsConfig::where('type', '12')
                        ->where('config_id', '1234')
                        ->first();
                }
                if ($config && $config->app_key && $phone && $password) {
                    $phone = trim($phone);
                    $sms_data = [
                        'Managee' => $phone,
                        'passwordd' => $password
                    ];
                    $sms_result = $this->sendSms($phone, $config->app_key, $config->app_secret, $config->SignName, $config->TemplateCode, $sms_data);
                    if ($sms_result->Code == 'OK') {
//                        Log::info('合伙人通知，'.$phone.'发送短信成功');
                    } else {
                        Log::info('合伙人通知，'.$phone.'发送短信失败: '.$sms_result->Message);
                    }
                }
            }

            return json_encode([
                'status' => 1,
                'message' => '下级账号添加成功',
                'data' => $request->except(['token'])
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }


    //修改代理或者自己的信息
    public function up_user(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id', $user->user_id);

            $data = $request->except(['token', 'password']);

            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }
            $user->update($data);
            $user->save();
            return json_encode([
                'status' => 1,
                'message' => '修改成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }


    //设置登录密码
    public function set_password(Request $request)
    {
        try {
            $user = $this->parseToken();
            $oldpassword = $request->get('oldpassword', '');
            $newpassword = $request->get('newpassword', '');
            $newpassword_confirmed = $request->get('newpassword_confirmed', '');


            $check_data = [
                'oldpassword' => '旧密码',
                'newpassword' => '新密码',
                'newpassword_confirmed' => '确认新密码'
            ];

            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $local = User::where('id', $user->user_id)->first();
            //验证旧的密码
            if (!Hash::check($oldpassword, $local->password)) {
                return json_encode([
                    'status' => 2,
                    'message' => '旧的登陆密码不匹配'
                ]);
            }
            if ($newpassword !== $newpassword_confirmed) {
                return json_encode([
                    'status' => 2,
                    'message' => '两次密码不一致'
                ]);
            }
            if (strlen($newpassword) < 6) {
                return json_encode([
                    'status' => 2,
                    'message' => '密码长度不符合要求'
                ]);
            }
            $dataIN = [
                'password' => bcrypt($newpassword),

            ];
            User::where('id', $user->user_id)->update($dataIN);


            $data = [
                'status' => 1,
                'message' => '密码修改成功',
            ];
            return json_encode($data);

        } catch (\Exception $exception) {
            return json_encode(['status' => 2, 'message' => $exception->getMessage()]);
        }
    }


    //修改登录手机号
    public function edit_login_phone(Request $request)
    {

        try {
            $user = $this->parseToken();
            $data = $request->all();
            $password = $request->get('password', '');
            $new_phone = $request->get('phone', '');
            $code_b = $request->get('code_b', '');
            //如果只传password代表校验
            if ($password && $new_phone == "" && $code_b == "") {
                //验证验证码
                $local = User::where('id', $user->user_id)->first();
                //验证旧的密码
                if (!Hash::check($password, $local->password)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '密码不匹配'
                    ]);
                } else {
                    return json_encode([
                        'status' => 1,
                        'message' => '密码匹配成功',
                    ]);
                }
            } else {
                if ($code_b && $new_phone == '' & $password == "") {
                    //验证新手机验证码
                    $msn_local = Cache::get($new_phone . 'editphone-1');
                    if ((string)$code_b != (string)$msn_local) {
                        return json_encode([
                            'status' => 2,
                            'message' => '新手机号码短信验证码不匹配'
                        ]);
                    } else {
                        return json_encode([
                            'status' => 1,
                            'message' => '短信验证码匹配成功',
                            'data' => [],
                        ]);
                    }
                }

                //换手机号码
                //验证新的手机号
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $new_phone)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '手机号码不正确'
                    ]);
                }
                if ($new_phone == $user->phone) {
                    return json_encode([
                        'status' => 2,
                        'message' => '手机号码未更改'
                    ]);
                }
                $rules = [
                    'phone' => 'required|min:11|max:11|unique:users',
                ];
                $validator = Validator::make($data, $rules);
                if ($validator->fails()) {
                    return json_encode([
                        'status' => 2,
                        'message' => '账号已注册请更换'
                    ]);
                }


                //验证新手机验证码
                $msn_local = Cache::get($new_phone . 'editphone-1');
                if ((string)$code_b != (string)$msn_local) {
                    return json_encode([
                        'status' => 2,
                        'message' => '新手机号码短信验证码不匹配'
                    ]);
                }

                User::where('id', $user->user_id)->update(['phone' => $new_phone]);


                $data = [
                    'status' => 1,
                    'message' => '手机号修改成功',
                ];
                return json_encode($data);

            }
        } catch
        (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    //删除代理
    public function del_sub_user(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id', '');
            $login_user_id = $user->user_id;
            $province_name = $request->get('province_name', '全国');
            $city_name = $request->get('city_name', '全国');
            $area_name = $request->get('area_name', '全国');
            $address = $request->get('address', '全国');


            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }


            $login_user = User::where('id', $login_user_id)->first();

            $hasPermission = $login_user->hasPermissionTo('删除下级代理');
            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '暂不支持删除下级代理']);
            }


            if ($user->user_id == $user_id) {
                return json_encode([
                    'status' => 2,
                    'message' => '不能删除自己'
                ]);
            }

            $users = $this->getSubIds($user_id);

            User::whereIn('id', $users)->update(['is_delete' => 1]);

            return json_encode([
                'status' => 1,
                'message' => '下级账号删除成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }
    
    //重置代理密码
    public function cz_user_password(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id', '');
            $login_user_id = $user->user_id;
            $province_name = $request->get('province_name', '全国');
            $city_name = $request->get('city_name', '全国');
            $area_name = $request->get('area_name', '全国');
            $address = $request->get('address', '全国');


            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }
            if($user->id=='1'){
                return json_encode([
                    'status' => 2,
                    'message' => '总账户不能重置'
                ]);
            }

            User::where('id', $user->id)->update(['password' => '$2y$10$zF9nWMXPNvf7sqiMDapQwueL5DFeYs.P.4gtJqeYjBJfWTR/0wNWG']);

            return json_encode([
                'status' => 1,
                'message' => '密码重置成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }

    //开通代理商服务费代扣
    public function server_sub_user(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id', '');

            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }


            User::where('id', $user_id)->update(['server_status' => 1]);

            return json_encode([
                'status' => 1,
                'message' => '操作成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }


    //彻底删除代理
    public function cdel_sub_user(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id', '');
            $level=$user->level;
            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }

            if ($user->user_id == $user_id) {
                return json_encode([
                    'status' => 2,
                    'message' => '不能删除自己'
                ]);
            }
            $sub_user = User::where('pid', $user_id)->first();
            if ($sub_user) {
                return json_encode([
                    'status' => 2,
                    'message' => '账户存在下级请先删除下级账户'
                ]);
            }

            $order = Order::where('user_id', $user_id)
                ->select('id')
                ->first();
            if ($level&&$order) {
                return json_encode([
                    'status' => 2,
                    'message' => '账户存在关联订单暂不支持删除'
                ]);
            }


            User::where('id', $user_id)->delete();

            return json_encode([
                'status' => 1,
                'message' => '下级账号清除成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }


    //恢复代理
    public function fog_sub_user(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id', '');
            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }

            if ($user->user_id == $user_id) {
                return json_encode([
                    'status' => 2,
                    'message' => '不能恢复自己'
                ]);
            }

            $user->update(['is_delete' => 0]);
            $user->save();

            return json_encode([
                'status' => 1,
                'message' => '下级账号恢复成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }


    //我的信息
    public function my_info(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;
            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }
            $sub = $this->getSubIds($user_id, false);
            $user->sub_user_count = "" . count($sub) . "";
            //默认头像
            if ($user->logo == "") {
                $user->logo = url('/app/img/user/fwslogo.png');
            }
            if($user->id=='426'){
                $user->logo_url='https://pay.zgjindoufu.com/wmzf.png';
            }else{
                $user->logo_url='http://wanfutong.oss-cn-hangzhou.aliyuncs.com/186055811861662021955.jpg';
            }
            return json_encode([
                'status' => 1,
                'message' => '查询成功',
                'data' => $user
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }
    //服务商小程序获取用户openid
    public function fuwushang_openid(Request $request){
        $code = $request->get('code');
        $url='https://api.weixin.qq.com/sns/jscode2session?appid=wx2101630f3dc4add0&secret=7bfa0969af783b4a6f91bf878535dc46&js_code='.$code.'&grant_type=authorization_code';
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl); //返回api的json对象
        curl_close($curl);
        return $tmpInfo; //返回json对象
        
    }
    
    public function tosign($data){
        ksort($data);
        $string=$this->tourlparams($data);
        $string=$string.'&key=q85KjBjKu33b5dMU8kp25F4g2oqFKaoX';
        $string=strtoupper(md5($string));
        return $string;
    }
    
    public function http_request_xml($data){
        $url='https://api.mch.weixin.qq.com/pay/unifiedorder';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    
    public function arr_to_xml($data, $root = true)
    {
        $str = "";
        if ($root) {
            $str .= "<xml>";
        }
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $child = arr_to_xml($val, false);
                $str .= "<$key>$child</$key>";
            } else {
                $str .= "<$key><![CDATA[$val]]></$key>";
            }
        }
        if ($root) {
            $str .= "</xml>";
        }
        return $str;
    }
    
    public function xml_to_array($xml)
    {
        if (!$xml) {
            die("xml数据异常！");
        }
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }
    
    public function tourlparams($params){
        $string='';
        if(!empty($params)){
            $array=array();
            foreach($params as $key=>$value){
                $array[]=$key.'='.$value;
            }
            $string=implode('&',$array);
        }
        return $string;
    }
    
    //小程序支付服务端处理
    public function smallpay(Request $request){
        try {
            $user_id = $request->get('user_id');
            $openid = $request->get('openid');
            $total_amount = $request->get('total_amount');
            $remark = $request->get('remark', '备注');
            $check_data = [
                'user_id' => '代理商ID',
                'total_amount' => '充值金额',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'deposit_status' => '3',
                    'message' => $check
                ]);
            }
            $out_order_no = 'wx' . time() . substr(microtime(), 2, 4);
            $nonce_str=md5(mt_rand(1000, 9999).time());
            $full_data=array(
                'store_id'=>0,
                'orderNo'=>$out_order_no,
                'total_price'=>$total_amount,
                'status'=>1,
                'created_at'=>time(),
                'updated_at'=>time(),
                'user_id'=>$user_id
            );
            DB::table('fullmoney_log')->insert($full_data);
            $data=array(
                'appid'=>'wx2101630f3dc4add0',
                'mch_id'=>'1509499221',
                'nonce_str'=>$nonce_str,
                'sign_type'=>'MD5',
                'body'=>'chongzhi',
                'out_trade_no'=>$out_order_no,
                'total_fee'=>$total_amount*100,
                'spbill_create_ip'=>$_SERVER['SERVER_ADDR'],
                'notify_url'=>url('/api/vbill/wufushang_notifyurl'),
                'trade_type'=>'JSAPI',
                'openid'=>$openid,
            );
            $sign=$this->tosign($data);
            $data['sign']=$sign;
            $data_xml=$this->arr_to_xml($data);
            $return=$this->http_request_xml($data_xml);
            $return_data=$this->xml_to_array($return);
            if($return_data['result_code']=='SUCCESS'){
                $time=time();
                $tmp['appId']='wx2101630f3dc4add0';
                $tmp['nonceStr']=$return_data['nonce_str'];
                $tmp['package']='prepay_id='.$return_data['prepay_id'];
                $tmp['signType']='MD5';
                $tmp['timeStamp']="$time";
                $data_tmp['status']=1;
                $data_tmp['timeStamp']="$time";
                $data_tmp['nonceStr']=$return_data['nonce_str'];
                $data_tmp['signType']='MD5';
                $data_tmp['package']='prepay_id='.$return_data['prepay_id'];
                $data_tmp['paySign']=$this->tosign($tmp);
                $data_tmp['out_trade_no']=$out_order_no;
            }
            return json_encode($data_tmp);
            
        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'deposit_status' => '3',
                'message' => $exception->getMessage(),
            ]);
        }
    }
    
    
    public function notify(Request $request){
        $orderNo = $request->get('orderNo');
        $log=DB::table('fullmoney_log')->where('orderNo', $orderNo)->first();
        $user=DB::table('users')->where('id', $log->user_id)->first();
        $settlement=$user->settlement_money+$log->total_price;
        if($log->status==1){
            DB::table('fullmoney_log')->where('orderNo', $orderNo)->update(array('status'=>2));
            DB::table('users')->where('id', $log->user_id)->update(array('settlement_money'=>$settlement));
        }
    }
    
    


    public function user_info(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id', '');
            $user = User::where('id', $user_id)->first();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }
            //默认头像
            if ($user->logo == "") {
                $user->logo = url('/app/img/user/fwslogo.png');
            }
            return json_encode([
                'status' => 1,
                'message' => '返回成功',
                'data' => $user
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }
    }


    //查询代理成本费率情况
    public function user_ways_all(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            
            // if($user->user_id !== 1){
            //     return json_encode([
            //         'status' => 2,
            //         'message' => "待开发"
            //     ]);
            // }

            $data = [];
            $store_ways_desc = DB::table('store_ways_desc')
                ->orderBy('company')
                ->get();
            foreach ($store_ways_desc as $k => $value) {
                $UserRate = UserRate::where('company', $value->company)
                    ->where('user_id', $user->user_id)
                    ->select('id')
                    ->first();
                if (!$UserRate) {
                    continue;
                }

                $has = UserRate::where('user_id', $user_id)->where('ways_type', $value->ways_type)->first();
                if ($has) {
                    $data[$k]['ways_type'] = $value->ways_type;
                    $data[$k]['status'] = $has->status;
                    $data[$k]['ways_desc'] = $value->ways_desc;
                    $data[$k]['rate'] = $has->rate;
                    $data[$k]['server_rate'] = $has->server_rate;
                    $data[$k]['yu_rate'] = $has->yu_rate;
                    $data[$k]['era_rate'] = $has->era_rate;
                    $data[$k]['rate_a'] = $has->rate_a;
                    $data[$k]['rate_b'] = $has->rate_b;
                    $data[$k]['rate_b_top'] = $has->rate_b_top;
                    $data[$k]['rate_c'] = $has->rate_c;
                    $data[$k]['rate_d'] = $has->rate_d;
                    $data[$k]['rate_d_top'] = $has->rate_d_top;
                    $data[$k]['rate_e'] = $has->rate_e;
                    $data[$k]['rate_f'] = $has->rate_f;
                    $data[$k]['rate_f_top'] = $has->rate_f_top;
                    $data = array_values($data);

                    //如果是刷卡费率读取
                    if (in_array($value->ways_type, [8005, 6005])) {
                        $data[$k]['rate'] = $has->rate_e;
                    }

                    //如果是银联扫码费率读取
                    if (in_array($value->ways_type, [8004, 6004])) {
                        $data[$k]['rate'] = $has->rate_a;
                    }
                } else {
                    $data[$k]['ways_type'] = $value->ways_type;
                    $data[$k]['ways_desc'] = $value->ways_desc;
                    $data[$k]['rate_a'] = $value->rate_a;
                    $data[$k]['rate_b'] = $value->rate_b;
                    $data[$k]['rate_b_top'] = $value->rate_b_top;
                    $data[$k]['rate_c'] = $value->rate_c;
                    $data[$k]['rate_d'] = $value->rate_d;
                    $data[$k]['rate_d_top'] = $value->rate_d_top;
                    $data[$k]['rate_e'] = $value->rate_e;
                    $data[$k]['rate_f'] = $value->rate_f;
                    $data[$k]['rate_f_top'] = $value->rate_f_top;
                    $data[$k]['rate'] = '';
                    $data[$k]['server_rate'] = '';
                    $data[$k]['yu_rate'] = '';
                    $data[$k]['era_rate'] = '';
                    $data[$k]['status'] = 2;
                }
            }

            return json_encode([
                'status' => 1,
                'data' => $data
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => '-1',
                'message' => $exception->getMessage().' | '.$exception->getFile().' | '.$exception->getLine()
            ]);
        }
    }
    
    //查询代理服务费成本费率情况
    public function server_ways_all(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $data = [];
            $store_ways_desc = DB::table('store_ways_desc')
                ->orderBy('company')
                ->get();
            foreach ($store_ways_desc as $k => $value) {
                $UserRate = ServerRate::where('company', $value->company)
                    ->where('user_id', $user->user_id)
                    ->select('id')
                    ->first();
                if (!$UserRate) {
                    continue;
                }

                $has =ServerRate::where('user_id', $user_id)->where('ways_type', $value->ways_type)->first();
                if ($has) {
                    $data[$k]['ways_type'] = $value->ways_type;
                    $data[$k]['status'] = $has->status;
                    $data[$k]['ways_desc'] = $value->ways_desc;
                    $data[$k]['rate'] = $has->rate;
                    $data[$k]['rate_a'] = $has->rate_a;
                    $data[$k]['rate_b'] = $has->rate_b;
                    $data[$k]['rate_b_top'] = $has->rate_b_top;
                    $data[$k]['rate_c'] = $has->rate_c;
                    $data[$k]['rate_d'] = $has->rate_d;
                    $data[$k]['rate_d_top'] = $has->rate_d_top;
                    $data[$k]['rate_e'] = $has->rate_e;
                    $data[$k]['rate_f'] = $has->rate_f;
                    $data[$k]['rate_f_top'] = $has->rate_f_top;
                    $data = array_values($data);

                    //如果是刷卡费率读取
                    if (in_array($value->ways_type, [8005, 6005])) {
                        $data[$k]['rate'] = $has->rate_e;
                    }

                    //如果是银联扫码费率读取
                    if (in_array($value->ways_type, [8004, 6004])) {
                        $data[$k]['rate'] = $has->rate_a;
                    }
                } else {
                    $data[$k]['ways_type'] = $value->ways_type;
                    $data[$k]['ways_desc'] = $value->ways_desc;
                    $data[$k]['rate_a'] = $value->rate_a;
                    $data[$k]['rate_b'] = $value->rate_b;
                    $data[$k]['rate_b_top'] = $value->rate_b_top;
                    $data[$k]['rate_c'] = $value->rate_c;
                    $data[$k]['rate_d'] = $value->rate_d;
                    $data[$k]['rate_d_top'] = $value->rate_d_top;
                    $data[$k]['rate_e'] = $value->rate_e;
                    $data[$k]['rate_f'] = $value->rate_f;
                    $data[$k]['rate_f_top'] = $value->rate_f_top;
                    $data[$k]['rate'] = '';
                    $data[$k]['status'] = 2;
                }
            }

            return json_encode([
                'status' => 1,
                'data' => $data
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => '-1',
                'message' => $exception->getMessage().' | '.$exception->getFile().' | '.$exception->getLine()
            ]);
        }
    }
    
    //修改代理带费率-扫码
    public function edit_server_rate(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            //扫码
            $rate = $request->get('rate');
            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }


            if ($user_id == $user->user_id && $user->level != 0) {
                return json_encode(['status' => 2, 'message' => '不能设置自己的费率请联系上级', 'data' => []]);
            }

            if ($rate > 1) {
                return json_encode(['status' => 2, 'message' => '费率超过系统上限', 'data' => []]);
            }

            //上级代理商的费率
            $user_pid_rate = ServerRate::where('user_id', $edit_user->pid)
                ->where('ways_type', $ways_type)
                ->select('rate')
                ->first();
            if (!$user_pid_rate&&$edit_user->pid) {
                return json_encode(['status' => 2, 'message' => '上级代理商未设置费率', 'data' => []]);
            }


            //被设置者是平台以下的账户不能大于上级的成本
            if ($edit_user->level > 0&&$edit_user->pid) {
                if ($rate < $user_pid_rate->rate) {
                    return json_encode(['status' => 2, 'message' => '费率不能低于上级代理商的费率', 'data' => []]);
                }
            }

            $astore_ways_desc = DB::table('store_ways_desc')
                ->where('ways_type', $ways_type)
                ->select('company')
                ->first();
            if (!$astore_ways_desc) {
                return json_encode(['status' => 2, 'message' => '通道基础数据不存在']);
            }

            //扫码需要参数
            $data = [
                'user_id' => $user_id,
                'rate' => $rate,
                'company' => $astore_ways_desc->company,
            ];

            $this->send_ways_data_server($data);

            return json_encode(['status' => 1, 'message' => '修改成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }
    
    public function send_ways_data_server($data)
    {
        try {
            //开启事务
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $data['company'])->get();
            foreach ($all_pay_ways as $k => $v) {
                $ways = ServerRate::where('user_id', $data['user_id'])->where('ways_type', $v->ways_type)
                    ->first();
                try {
                    DB::beginTransaction();
                    $data = [
                        'rate' => $data['rate'],
                        'settlement_type' => $v->settlement_type,
                        'user_id' => $data['user_id'],
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                    ];
                    if ($ways) {
                        $ways->update($data);
                        $ways->save();
                    } else {
                        ServerRate::create($data);
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return [
                        'status' => 2,
                        'message' => '通道入库更新失败',
                    ];
                }
            }


            return [
                'status' => $data['status'],
                'message' => $data['status_desc'],
            ];

        } catch (\Exception $e) {
            return [
                'status' => 2,
                'message' => '通道入库更新失败',
            ];
        }
    }


    //查询代理各个通道商户的默认费率
    public function user_ways_default(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');

            $data = [];
            $store_ways_desc = DB::table('store_ways_desc')->get();
            foreach ($store_ways_desc as $k => $value) {

                //代理不开通不
                $UserRate = UserRate::where('company', $value->company)
                    ->where('user_id', $user_id)
                    ->select('id')
                    ->first();

                if (!$UserRate) {
                    continue;
                }

                $has = UserRate::where('user_id', $user_id)->where('ways_type', $value->ways_type)->first();
                if ($has) {
                    $data[$k]['ways_type'] = $value->ways_type;
                    $data[$k]['ways_desc'] = $value->ways_desc;
                    $data[$k]['store_all_rate'] = $has->store_all_rate;
                    $data[$k]['store_all_rate_a'] = $has->store_all_rate_a;
                    $data[$k]['store_all_rate_b'] = $has->store_all_rate_b;
                    $data[$k]['store_all_rate_b_top'] = $has->store_all_rate_b_top;
                    $data[$k]['store_all_rate_c'] = $has->store_all_rate_c;
                    $data[$k]['store_all_rate_d'] = $has->store_all_rate_d;
                    $data[$k]['store_all_rate_d_top'] = $has->store_all_rate_d_top;
                    $data[$k]['store_all_rate_e'] = $has->store_all_rate_e;
                    $data[$k]['store_all_rate_f'] = $has->store_all_rate_f;
                    $data[$k]['store_all_rate_f_top'] = $has->store_all_rate_f_top;


                    //如果是刷卡费率读取
                    //新大陆刷卡
                    if (in_array($value->ways_type, [8005, 6005])) {

                        $data[$k]['store_all_rate'] = $has->store_all_rate_e;
                    }

                    //银联扫码
                    if (in_array($value->ways_type, [8004, 6004])) {
                        $data[$k]['store_all_rate'] = $has->store_all_rate_a;
                    }


                    $data = array_values($data);


                } else {
                    $data[$k]['ways_type'] = $value->ways_type;
                    $data[$k]['ways_desc'] = $value->ways_desc;
                    $data[$k]['store_all_rate'] = $value->store_all_rate;
                    $data[$k]['store_all_rate_a'] = $value->store_all_rate_a;
                    $data[$k]['store_all_rate_b'] = $value->store_all_rate_b;
                    $data[$k]['store_all_rate_b_top'] = $value->store_all_rate_b_top;
                    $data[$k]['store_all_rate_c'] = $value->store_all_rate_c;
                    $data[$k]['store_all_rate_d'] = $value->store_all_rate_d;
                    $data[$k]['store_all_rate_d_top'] = $value->store_all_rate_d_top;
                    $data[$k]['store_all_rate_e'] = $value->store_all_rate_e;
                    $data[$k]['store_all_rate_f'] = $value->store_all_rate_f;
                    $data[$k]['store_all_rate_f_top'] = $value->store_all_rate_f_top;
                    //如果是刷卡费率读取
                    //新大陆刷卡
                    if (in_array($value->ways_type, [8005, 6005])) {

                        $data[$k]['store_all_rate'] = $value->store_all_rate_e;
                    }

                    //银联扫码
                    if (in_array($value->ways_type, [8004, 6004])) {
                        $data[$k]['store_all_rate'] = $value->store_all_rate_a;
                    }


                }

            }

            return json_encode(['status' => 1, 'data' => $data]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }
    }


    //修改代理带费率-扫码
    public function edit_user_rate(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            //扫码
            $rate = $request->get('rate');//通道费率
            $server_rate = $request->get('server_rate');//服务费费率
            $yu_rate = $request->get('yu_rate');//预充费率
            $era_rate = $request->get('era_rate');//代扣费率
            if(empty($rate)||empty($server_rate)||empty($yu_rate)||empty($era_rate)){
                return json_encode(['status' => 2, 'message' => '成本费率全部不能为空', 'data' => []]);
            }
            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }


            if ($user_id == $user->user_id && $user->level != 0) {
                return json_encode(['status' => 2, 'message' => '不能设置自己的费率请联系上级', 'data' => []]);
            }

            if ($rate > 1 || $server_rate > 1 ||$yu_rate > 1||$era_rate > 1) {
                return json_encode(['status' => 2, 'message' => '费率超过系统上限', 'data' => []]);
            }

            //上级代理商的费率
            $user_pid_rate = UserRate::where('user_id', $edit_user->pid)
                ->where('ways_type', $ways_type)
                ->select('rate')
                ->first();
            if (!$user_pid_rate&&$edit_user->pid) {
                return json_encode(['status' => 2, 'message' => '上级代理商未设置费率', 'data' => []]);
            }


            //被设置者是平台以下的账户不能大于上级的成本
            if ($edit_user->level > 0&&$edit_user->pid) {
                if ($rate < $user_pid_rate->rate) {
                    return json_encode(['status' => 2, 'message' => '费率不能低于上级代理商的费率', 'data' => []]);
                }
            }

            $astore_ways_desc = DB::table('store_ways_desc')
                ->where('ways_type', $ways_type)
                ->select('company')
                ->first();
            if (!$astore_ways_desc) {
                return json_encode(['status' => 2, 'message' => '通道基础数据不存在']);
            }

            //扫码需要参数
            $data = [
                'user_id' => $user_id,
                'rate' => $rate,
                'server_rate' => $server_rate,
                'yu_rate' => $yu_rate,
                'era_rate' => $era_rate,
                'company' => $astore_ways_desc->company,
            ];


            $this->send_ways_data($data);

            return json_encode(['status' => 1, 'message' => '修改成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }


    //关停和删除通道
    public function del_user_rate(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');
            $status = $request->get('status', '2');
            //
            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }

            if ($user->pid&&$status=='1') {
                return json_encode(['status' => 2, 'message' => '暂不支持开启', 'data' => []]);
            }

            $arr = $this->getSubIds($user->user_id);

            if (!in_array($user_id, $arr)) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }


            UserRate::where('ways_type', $ways_type)
                ->where('user_id', $user_id)
                ->update(['status' => $status]);


            return json_encode(['status' => 1, 'message' => '操作成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }


    //修改代理带费率-刷卡
    public function edit_user_un_rate(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            $rate_e = $request->get('rate_e');
            $rate_f = $request->get('rate_f');
            $rate_f_top = $request->get('rate_f_top', '20');

            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }


            if ($user_id == $user->user_id && $user->level != 0) {
                return json_encode(['status' => 2, 'message' => '不能设置自己的费率请联系上级', 'data' => []]);
            }

            //上级代理商的费率
            $user_pid_rate = UserRate::where('user_id', $edit_user->pid)
                ->where('ways_type', $ways_type)
                ->select('rate_e', 'rate_f')
                ->first();

            if (!$user_pid_rate&&$edit_user->pid) {
                return json_encode(['status' => 2, 'message' => '上级代理商未设置费率', 'data' => []]);
            }

            //被设置者是平台以下的账户不能大于上级的成本
            if ($edit_user->level > 0) {
                //不能大于代理商的成本
                if ($rate_e < $user_pid_rate->rate_e) {
                    return json_encode(['status' => 2, 'message' => '贷记卡费率不能低于上级代理商的费率', 'data' => []]);
                }
                //不能大于代理商的成本
                if ($rate_f < $user_pid_rate->rate_f) {
                    return json_encode(['status' => 2, 'message' => '借记卡费率不能低于上级代理商的费率', 'data' => []]);
                }
            }

            $astore_ways_desc = DB::table('store_ways_desc')
                ->where('ways_type', $ways_type)
                ->select('company')
                ->first();
            if (!$astore_ways_desc) {
                return json_encode(['status' => 2, 'message' => '通道基础数据不存在']);
            }


            $ways = UserRate::where('user_id', $user_id)->where('ways_type', $ways_type)->first();

            //请先设置扫码通道的费率
            if (!$ways) {
                return json_encode(['status' => 2, 'message' => '请先设置扫码通道的费率']);
            }

            $company = $ways->company;
            $data = [
                'rate_e' => $rate_e,
                'rate_f' => $rate_f,
                'rate_f_top' => $rate_f_top,
            ];
            UserRate:: where('user_id', $user_id)->where('company', $company)
                ->update($data);


            return json_encode(['status' => 1, 'message' => '修改成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }


    //修改代理带费率-银联扫码
    public function edit_user_unqr_rate(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            $rate_a = $request->get('rate_a');
            $rate_b = $request->get('rate_b');
            $rate_b_top = $request->get('rate_b_top', '20');
            $rate_c = $request->get('rate_c');
            $rate_d = $request->get('rate_d');
            $rate_d_top = $request->get('rate_d_top', '20');

            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }


            //上级代理商的费率
            $user_pid_rate = UserRate::where('user_id', $edit_user->pid)
                ->where('ways_type', $ways_type)
                ->select('rate_a', 'rate_b', 'rate_c', 'rate_d')
                ->first();
            if (!$user_pid_rate&&$edit_user->pid!="0") {
                return json_encode(['status' => 2, 'message' => '上级代理商未设置费率', 'data' => []]);
            }

            if ($user_id == $user->user_id && $user->level != 0) {
                return json_encode(['status' => 2, 'message' => '不能设置自己的费率请联系上级', 'data' => []]);
            }

            //被设置者是平台以下的账户不能大于上级的成本
            if ($edit_user->level > 0) {
                //不能大于代理商的成本
                if ($rate_a < $user_pid_rate->rate_a) {
                    return json_encode(['status' => 2, 'message' => '小于1000贷记卡费率不能低于上级代理商的费率', 'data' => []]);
                }
                //不能大于代理商的成本
                if ($rate_b < $user_pid_rate->rate_b) {
                    return json_encode(['status' => 2, 'message' => '小于1000借记卡费率不能低于上级代理商的费率', 'data' => []]);
                }

                //不能大于代理商的成本
                if ($rate_c < $user_pid_rate->rate_c) {
                    return json_encode(['status' => 2, 'message' => '大于1000贷记卡费率不能低于上级代理商的费率', 'data' => []]);
                }
                //不能大于代理商的成本
                if ($rate_d < $user_pid_rate->rate_d) {
                    return json_encode(['status' => 2, 'message' => '大于1000借记卡费率不能低于上级代理商的费率', 'data' => []]);
                }

            }

            $astore_ways_desc = DB::table('store_ways_desc')
                ->where('ways_type', $ways_type)
                ->select('company')
                ->first();
            if (!$astore_ways_desc) {
                return json_encode(['status' => 2, 'message' => '通道基础数据不存在']);
            }


            $ways = UserRate::where('user_id', $user_id)->where('ways_type', $ways_type)->first();

            //请先设置扫码通道的费率
            if (!$ways) {
                return json_encode(['status' => 2, 'message' => '请先设置扫码通道的费率']);
            }
            $company = $ways->company;

            $data = [
                'rate_a' => $rate_a,
                'rate_b' => $rate_b,
                'rate_b_top' => $rate_b_top,
                'rate_c' => $rate_c,
                'rate_d' => $rate_d,
                'rate_d_top' => $rate_d_top,
            ];

            UserRate::where('user_id', $user_id)->where('company', $company)->update($data);


            return json_encode(['status' => 1, 'message' => '修改成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }


    //修改商户统一默认费率-扫码
    public function edit_user_store_all_rate(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            //扫码
            $store_all_rate = $request->get('store_all_rate');
            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }

            if ($store_all_rate > 1) {
                return json_encode(['status' => 2, 'message' => '费率超过系统上限', 'data' => []]);
            }

            //自己的费率
            $user_rate = UserRate::where('user_id', $user_id)
                ->where('ways_type', $ways_type)
                ->first();
            if (!$user_rate) {
                return json_encode(['status' => 2, 'message' => '通道成本费率未设置请联系上级', 'data' => []]);

            }

            //不能小于自己的成本
            if ($store_all_rate < $user_rate->rate) {
                return json_encode(['status' => 2, 'message' => '费率不能低于成本费率', 'data' => []]);
            }


            $astore_ways_desc = DB::table('store_ways_desc')
                ->where('ways_type', $ways_type)
                ->select('company')
                ->first();
            if (!$astore_ways_desc) {
                return json_encode(['status' => 2, 'message' => '通道基础数据不存在']);
            }

            //扫码需要参数
            $data = [
                'user_id' => $user_id,
                'store_all_rate' => $store_all_rate,
                'company' => $astore_ways_desc->company,
            ];


            $this->send_ways_store_all_data($data);

            return json_encode(['status' => 1, 'message' => '修改成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }


    //修改商户默认统一费率-刷卡
    public function edit_user_un_store_all_rate(Request $request)
    {

        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            $store_all_rate_e = $request->get('store_all_rate_e');
            $store_all_rate_f = $request->get('store_all_rate_f');
            $store_all_rate_f_top = $request->get('store_all_rate_f_top', '20');

            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }


            //自己的费率
            $user_rate = UserRate::where('user_id', $user_id)
                ->where('ways_type', $ways_type)
                ->first();

            if (!$user_rate) {
                return json_encode(['status' => 2, 'message' => '通道成本费率未设置请联系上级', 'data' => []]);

            }

            //不能小于自己的成本
            if ($store_all_rate_e < $user_rate->rate_e) {
                return json_encode(['status' => 2, 'message' => '贷记卡费率不能低于成本费率', 'data' => []]);
            }
            //不能小于自己的成本
            if ($store_all_rate_f < $user_rate->rate_f) {
                return json_encode(['status' => 2, 'message' => '借记卡费率不能低于成本费率', 'data' => []]);
            }

            //不能小于自己的成本
            if ($store_all_rate_f_top < $user_rate->rate_f_top) {
                return json_encode(['status' => 2, 'message' => '借记卡封顶金额不能小于成本', 'data' => []]);
            }


            $astore_ways_desc = DB::table('store_ways_desc')
                ->where('ways_type', $ways_type)
                ->select('company')
                ->first();
            if (!$astore_ways_desc) {
                return json_encode(['status' => 2, 'message' => '通道基础数据不存在']);
            }


            $ways = UserRate::where('user_id', $user_id)->where('ways_type', $ways_type)->first();

            //请先设置扫码通道的费率
            if (!$ways) {
                return json_encode(['status' => 2, 'message' => '请先设置扫码通道的费率']);
            }
            $company = $ways->company;

            $data = [
                'store_all_rate_e' => $store_all_rate_e,
                'store_all_rate_f' => $store_all_rate_f,
                'store_all_rate_f_top' => $store_all_rate_f_top,
            ];

            UserRate::where('user_id', $user_id)->where('company', $company)->update($data);


            return json_encode(['status' => 1, 'message' => '修改成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }


    //修改商户默认统一费率-银联扫码
    public function edit_user_unqr_store_all_rate(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            $store_all_rate_a = $request->get('store_all_rate_a');
            $store_all_rate_b = $request->get('store_all_rate_b');
            $store_all_rate_b_top = $request->get('store_all_rate_b_top', '20');
            $store_all_rate_c = $request->get('store_all_rate_c');
            $store_all_rate_d = $request->get('store_all_rate_d');
            $store_all_rate_d_top = $request->get('store_all_rate_d_top', '20');

            $edit_user = User::where('id', $user_id)->first();
            if (!$edit_user) {
                return json_encode(['status' => 2, 'message' => '代理商不存在', 'data' => []]);
            }


            //自己的费率
            $user_rate = UserRate::where('user_id', $user_id)
                ->where('ways_type', $ways_type)
                ->first();

            if (!$user_rate) {
                return json_encode(['status' => 2, 'message' => '通道成本费率未设置请联系上级', 'data' => []]);

            }
            //不能小于自己的成本
            if ($store_all_rate_a < $user_rate->rate_a) {
                return json_encode(['status' => 2, 'message' => '小于1000贷记卡费率不能低于自己的成本', 'data' => []]);
            }

            //不能小于自己的成本
            if ($store_all_rate_b < $user_rate->rate_b) {
                return json_encode(['status' => 2, 'message' => '小于1000借记卡费率不能低于自己的成本', 'data' => []]);
            }

            //不能小于自己的成本
            if ($store_all_rate_b_top < $user_rate->rate_b_top) {
                return json_encode(['status' => 2, 'message' => '小于1000借记卡封顶金额不能小于自己的成本', 'data' => []]);
            }


            //不能小于自己的成本
            if ($store_all_rate_c < $user_rate->rate_c) {
                return json_encode(['status' => 2, 'message' => '大于1000贷记卡费率不能低于自己的成本', 'data' => []]);
            }
            //不能小于自己的成本
            if ($store_all_rate_d < $user_rate->rate_d) {
                return json_encode(['status' => 2, 'message' => '大于1000借记卡费率不能低于自己的成本', 'data' => []]);
            }

            //不能小于自己的成本
            if ($store_all_rate_d_top < $user_rate->rate_d_top) {
                return json_encode(['status' => 2, 'message' => '大于1000借记卡封顶金额不能小于自己的成本', 'data' => []]);
            }


            $astore_ways_desc = DB::table('store_ways_desc')
                ->where('ways_type', $ways_type)
                ->select('company')
                ->first();
            if (!$astore_ways_desc) {
                return json_encode(['status' => 2, 'message' => '通道基础数据不存在']);
            }


            $ways = UserRate::where('user_id', $user_id)->where('ways_type', $ways_type)->first();

            //请先设置扫码通道的费率
            if (!$ways) {
                return json_encode(['status' => 2, 'message' => '请先设置扫码通道的费率']);
            }
            $company = $ways->company;

            $data = [
                'store_all_rate_a' => $store_all_rate_a,
                'store_all_rate_b' => $store_all_rate_b,
                'store_all_rate_b_top' => $store_all_rate_b_top,
                'store_all_rate_c' => $store_all_rate_c,
                'store_all_rate_d' => $store_all_rate_d,
                'store_all_rate_d_top' => $store_all_rate_d_top,
            ];


            UserRate::where('user_id', $user_id)->where('company', $company)
                ->update($data);


            return json_encode(['status' => 1, 'message' => '修改成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }

    }


    //查询单个通道详细
    public function user_ways_info(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $request->get('user_id');
            $ways_type = $request->get('ways_type');

            $data = [];
            $store_ways_desc = DB::table('store_ways_desc')->where('ways_type', $ways_type)->first();
            $data['ways_desc'] = $store_ways_desc->ways_desc;
            $data['ways_source'] = $store_ways_desc->ways_source;
            $data['settlement_type'] = $store_ways_desc->settlement_type;
            $data['ways_type'] = $store_ways_desc->ways_type;

            $has = UserRate::where('user_id', $user_id)->where('ways_type', $ways_type)->first();
            if ($has) {
                $data['rate'] = $has->rate;
                $data['rate_a'] = $has->rate_a;
                $data['rate_b'] = $has->rate_b;
                $data['rate_b_top'] = $has->rate_b_top;
                $data['rate_c'] = $has->rate_c;
                $data['rate_d'] = $has->rate_d;
                $data['rate_d_top'] = $has->rate_d_top;
                $data['store_all_rate'] = $has->store_all_rate;
                $data['store_all_rate_a'] = $has->store_all_rate_a;
                $data['store_all_rate_b'] = $has->store_all_rate_b;
                $data['store_all_rate_b_top'] = $has->store_all_rate_b_top;
                $data['store_all_rate_c'] = $has->store_all_rate_c;
                $data['store_all_rate_d'] = $has->store_all_rate_d;
                $data['store_all_rate_d_top'] = $has->store_all_rate_d_top;

            } else {
                $data['rate'] = '';
                $data['store_all_rate'] = '';
                $data['rate_a'] = '';
                $data['rate_b'] = '';
                $data['rate_b_top'] = '';
                $data['store_all_rate_a'] = '';
                $data['store_all_rate_b'] = '';
                $data['store_all_rate_b_top'] = '';
                $data['rate_c'] = '';
                $data['rate_d'] = '';
                $data['rate_d_top'] = '';
                $data['store_all_rate_c'] = '';
                $data['store_all_rate_d'] = '';
                $data['store_all_rate_d_top'] = '';
            }


            return json_encode(['status' => 1, 'data' => $data]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }
    }


    //添加支付密码
    public function add_pay_password(Request $request)
    {
        $rsa = new RsaE();
        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;

            //客户端用的我的公钥加密 我用私钥解密
            $data = $rsa->privDecrypt($request->get('sign'));//解密
            parse_str($data, $output);
            $pay_password = isset($output['pay_password']) ? $output['pay_password'] : "";
            $pay_password_confirmed = isset($output['pay_password_confirmed']) ? $output['pay_password_confirmed'] : "";

            if ($pay_password !== $pay_password_confirmed) {
                return json_encode([
                    'status' => 2,
                    'message' => '两次密码不一致'
                ]);
            }

            if ($pay_password) {
                //验证密码
                if (strlen($pay_password) != 6) {
                    return json_encode([
                        'status' => 2,
                        'message' => '密码长度不符合要求'
                    ]);
                }
                $dataIN = [
                    'pay_password' => bcrypt($pay_password),

                ];
                User::where('id', $user_id)->update($dataIN);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => '参数填写不完整'
                ]);
            }

            return json_encode([
                'status' => 1,
                'message' => '支付密码添加成功',
            ]);


        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //修改支付密码
    public function edit_pay_password(Request $request)
    {
        $rsa = new RsaE();
        try {
            $data = $rsa->privDecrypt($request->get('sign'));//解密
            parse_str($data, $output);
            $user = $this->parseToken();
            $user_id = $user->user_id;

            $oldpassword = isset($output['old_pay_password']) ? $output['old_pay_password'] : "";
            $newpassword = isset($output['new_pay_password']) ? $output['new_pay_password'] : "";

            if ($oldpassword && $newpassword == "") {
                $local = User::where('id', $user_id)->first();
                if (!Hash::check($oldpassword, $local->pay_password)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '旧的支付密码不匹配'
                    ]);
                } else {
                    return json_encode([
                        'status' => 1,
                        'message' => '旧的支付密码匹配'
                    ]);
                }
            }

            if (strlen($newpassword) != 6) {
                return json_encode([
                    'status' => 2,
                    'message' => '密码长度不符合要求'
                ]);
            }
            $dataIN = [
                'pay_password' => bcrypt($newpassword),

            ];

            User::where('id', $user_id)->update($dataIN);

            return json_encode([
                'status' => 1,
                'message' => '支付密码修改成功',
                'data' => []
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //忘记支付密码
    public function forget_pay_password(Request $request)
    {
        $rsa = new RsaE();
        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;
            //客户端用的我的公钥加密 我用私钥解密
            $data = $rsa->privDecrypt($request->get('sign'));//解密
            parse_str($data, $output);
            $newpassword = isset($output['new_pay_password']) ? $output['new_pay_password'] : "";
            $code = isset($output['code']) ? $output['code'] : "";
            $msn_local = Cache::get($user->phone . 'editpassword-1');
            //验证验证码
            if ($code != "" && $newpassword == "") {
                if ($code != $msn_local) {
                    return json_encode([
                        'status' => 2,
                        'message' => '短信验证码不匹配'
                    ]);
                } else {
                    return json_encode([
                        'status' => 1,
                        'message' => '短信验证码正确'
                    ]);
                }
            }

            //验证密码
            if (strlen($newpassword) < 6) {
                return json_encode([
                    'status' => 2,
                    'message' => '密码长度不符合要求'
                ]);
            }


            $User = User::where('id', $user_id)->first();

            //验证验证码
            $msn_local = Cache::get($User->phone . 'editpassword-1');
            if ((string)$code != (string)$msn_local) {
                return json_encode([
                    'status' => 2,
                    'message' => '短信验证码不匹配'
                ]);
            }

            $User->update(['pay_password' => bcrypt($newpassword)]);
            $User->save();

            return json_encode([
                'status' => 1,
                'message' => '支付密码修改成功',
                'data' => [],
            ]);


        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }

    }


    //校验支付密码
    public function check_pay_password(Request $request)
    {
        $rsa = new RsaE();
        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;
            $data = $rsa->privDecrypt($request->get('sign'));//解密
            parse_str($data, $output);

            $pay_password = isset($output['pay_password']) ? $output['pay_password'] : "";


            if (strlen($pay_password) != 6) {
                return json_encode([
                    'status' => 2,
                    'message' => '密码长度不符合要求'
                ]);
            }
            $local_pay_password = User::where('id', $user_id)->first();
            if ($local_pay_password && $local_pay_password->pay_password) {
                if (Hash::check($pay_password, $local_pay_password->pay_password)) {
                    return json_encode([
                        'status' => 1,
                        'message' => '支付密码匹配'
                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => '支付密码不匹配'
                    ]);
                }
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => '账号未设置支付密码'
                ]);
            }


        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //检测是否设置过支付密码
    public function is_pay_password(Request $request)
    {
        $user = $this->parseToken();
        $user_id = $user->user_id;
        $User = User::where('id', $user_id)->first();

        if ($User->pay_password) {

            $is_pay_password = 1;
        } else {
            $is_pay_password = 0;
        }

        return json_encode([
            'status' => 1,
            'data' => [
                'is_pay_password' => $is_pay_password,
            ]
        ]);
    }


    public function send_ways_data($data)
    {
        try {
            //开启事务
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $data['company'])->get();
            foreach ($all_pay_ways as $k => $v) {
                $ways = UserRate::where('user_id', $data['user_id'])->where('ways_type', $v->ways_type)
                    ->first();
                try {
                    DB::beginTransaction();
                    $data = [
                        'rate' => $data['rate'],
                        'server_rate' => $data['server_rate'],
                        'yu_rate' => $data['yu_rate'],
                        'era_rate' => $data['era_rate'],
                        'settlement_type' => $v->settlement_type,
                        'user_id' => $data['user_id'],
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                    ];
                    if ($ways) {
                        $ways->update($data);
                        $ways->save();
                    } else {
                        UserRate::create($data);
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return [
                        'status' => 2,
                        'message' => '通道入库更新失败',
                    ];
                }
            }


            return [
                'status' => $data['status'],
                'message' => $data['status_desc'],
            ];

        } catch (\Exception $e) {
            return [
                'status' => 2,
                'message' => '通道入库更新失败',
            ];
        }
    }


    public function send_ways_store_all_data($data)
    {
        try {
            //开启事务
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $data['company'])->get();
            foreach ($all_pay_ways as $k => $v) {
                $ways = UserRate::where('user_id', $data['user_id'])->where('ways_type', $v->ways_type)
                    ->first();
                try {
                    DB::beginTransaction();
                    $data = [
                        'store_all_rate' => $data['store_all_rate'],
                        'settlement_type' => $v->settlement_type,
                        'user_id' => $data['user_id'],
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                    ];
                    if ($ways) {
                        $ways->update($data);
                        $ways->save();
                    } else {
                        UserRate::create($data);
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return [
                        'status' => 2,
                        'message' => '通道入库更新失败',
                    ];
                }
            }


            return [
                'status' => $data['status'],
                'message' => $data['status_desc'],
            ];

        } catch (\Exception $e) {
            return [
                'status' => 2,
                'message' => '通道入库更新失败',
            ];
        }
    }


    //登录人修改密码
    public function edit_pwd(Request $request)
    {
        try {
            $token = $this->parseToken();

            $old_pwd = $request->get('old_pwd', '');
            $new_pwd = $request->get('new_pwd', '');
            $re_new_pwd = $request->get('re_new_pwd', '');

            $check_data = [
                'old_pwd' => '旧密码',
                'new_pwd' => '新密码',
                're_new_pwd' => '确认新密码'
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $user_info = User::where('id', $token->user_id)
                ->where('is_delete', '0')
                ->first();
            if ($user_info) {
                //验证旧的密码
                if (!Hash::check($old_pwd, $user_info->password)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '旧的登陆密码不匹配'
                    ]);
                }
                if ($new_pwd !== $re_new_pwd) {
                    return json_encode([
                        'status' => 2,
                        'message' => '两次密码不一致'
                    ]);
                }
                if (strlen($new_pwd) < 6) {
                    return json_encode([
                        'status' => 2,
                        'message' => '密码长度不能低于6位'
                    ]);
                }
                $dataIN = [
                    'password' => bcrypt($new_pwd),
                ];
                $res = $user_info->update($dataIN);
                if ($res) {
                    $data = [
                        'status' => 1,
                        'message' => '密码修改成功',
                    ];
                } else {
                    $data = [
                        'status' => 2,
                        'message' => '密码修改失败',
                    ];
                }

                return json_encode($data);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => '用户不存在或状态异常'
                ]);
            }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    public function sendSms($phone, $app_key, $app_secret, $SignName, $TemplateCode, $data)
    {
        $demo = new AliSms($app_key, $app_secret);
        $response = $demo->sendSms(
            $SignName, // 短信签名
            $TemplateCode, // 短信模板编号
            $phone, // 短信接收者
            $data
        );

        return $response;
    }


    //添加下级业务员
//    public function add_sub_user_new(Request $request)
//    {
//        try {
//            $token = $this->parseToken();
//            $login_user_id = $token->user_id;
//
//            $pid_name = $request->get('pid_name'); //上级公司名称
//            $level = $request->get('level'); //等级
//            $sub_profit_ratio = $request->get('subProfitRatio', '');  //下级利润比例%
//            $profit_ratio = $request->get('profitRatio', '');  //利润比例%
//
//            $phone = $request->get('phone'); //手机号
//            $password = $request->get('password'); //密码
//            $name = $request->get('user_name'); //公司名称
//            $people = $request->get('people', ''); //联系人姓名
//            $province_name = $request->get('province_name', '全国');
//            $city_name = $request->get('city_name', '全国');
//            $area_name = $request->get('area_name', '全国');
//            $address = $request->get('address', '全国');
//            $p_id = $request->get('pid', '');  //上级id
//            $p_id = isset($p_id) ? $p_id : $token->user_id;
//
//            $pid_user = User::where('id', $p_id)
//                ->where('is_delete', '0')
//                ->first();
//            if (!$pid_user) {
//                return json_encode([
//                    'status'=>'2',
//                    'message'=>'上级代理不存在或状态异常'
//                ]);
//            }
//
//            $login_user = User::where('id', $login_user_id)->first();
//            $hasPermission = $login_user->hasPermissionTo('添加下级代理');
//            if (!$hasPermission) {
//                return json_encode([
//                    'status' => 2,
//                    'message' => '暂不支持添加下级代理'
//                ]);
//            }
//
//            //4级以后如果没有开权限就不能在开了
////            if ($token->level > 5) {
////                return json_encode([
////                    'status' => 2,
////                    'message' => '暂不支持开下级账户'
////                ]);
////            }
//
//            $s_code = rand(1000, 9999);
//            $check_data = [
//                'phone' => '手机号',
//                'password' => '密码',
//                'user_name' => '公司名字',
//                'people' => '联系人姓名'
//            ];
//            $check = $this->check_required($request->except(['token']), $check_data);
//            if ($check) {
//                return json_encode([
//                    'status' => '2',
//                    'message' => $check
//                ]);
//            }
//
//            //验证手机号
//            if (!preg_match("/^1[3456789]{1}\d{9}$/", $phone)) {
//                return json_encode([
//                    'status' => '0',
//                    'message' => '手机号码不正确'
//                ]);
//            }
//
//            $data = $request->all();
//            $rules = [
//                'phone' => 'required|min:11|max:11|unique:users',
//            ];
//            $validator = Validator::make($data, $rules);
//            if ($validator->fails()) {
//                return json_encode([
//                    'status' => '2',
//                    'message' => '账号已注册请直接登录'
//                ]);
//            }
//
//            $rules = [
//                's_code' => 'required|min:4|max:4|unique:users',
//            ];
//            $validator = Validator::make(['s_code' => $s_code], $rules);
//            if ($validator->fails()) {
//                return json_encode([
//                    'status' => '2',
//                    'message' => '激活码生成失败，请重新提交资料'
//                ]);
//            }
//
//            //验证密码
//            if (strlen($password) < 6) {
//                return json_encode([
//                    'status' => 2,
//                    'message' => '密码长度不得少于6位'
//                ]);
//            }
//
//            $level_name = "业务员";
//            if ($level == 1) {
//                $level_name = "服务商";
//            }
//            if ($level == 2) {
//                $level_name = "代理商";
//            }
//
////            $level_name=$request->get('level_name',$level_name); //展示名称
//            $dataIn['config_id'] = $pid_user->config_id;
//            $dataIn['email'] = $phone . '@139.com';
//            $dataIn['level'] = $level;
//            $dataIn['level_name'] = $level_name;
//            $dataIn['logo'] = $people;  //联系人姓名
//            $dataIn['password'] = bcrypt($password);
//            $dataIn['name'] = $name;
//            $dataIn['phone'] = $phone;
//            $dataIn['s_code'] = $s_code;
//            $dataIn['pid'] = $p_id;
//            $dataIn['pid_name'] = $pid_name;
//            $dataIn['province_name'] = $province_name;
//            $dataIn['city_name'] = $city_name;
//            $dataIn['area_name'] = $area_name;
//            $dataIn['address'] = $address;
//            if (isset($profit_ratio) && $profit_ratio) { //分润比例
//                $dataIn['profit_ratio'] = $profit_ratio;
//            } else {
//                $dataIn['profit_ratio'] = $pid_user->sub_profit_ratio;
//            }
//            if (isset($sub_profit_ratio) && $sub_profit_ratio) $dataIn['sub_profit_ratio'] = $sub_profit_ratio; //下级分润比例
//            $dataIn['s_code_url'] = url('/api/user/s_code_url?s_code=' . $s_code);
//            $dataIn['sub_code_url'] = url('/api/user/sub_code_url?s_code=' . $s_code);
//
//            //超级服务商
//            if ($pid_user->pid == 0) {
//                $dataIn['config_id'] = $phone;
//                $dataIn['level'] = 1;
//            }
//
//            $User = User::create($dataIn);
//
//            //自动分配权限
//            try {
//                $user_id = $User->id;
//                $user = User::where('id', $user_id)->first();
//                $Permission = Role::where('display_name', $level_name)->first();
//                if ($Permission) {
//                    $user->assignRole($Permission->id);
//                }
//            } catch (\Exception $ex) {
//                Log::info('添加代理商-错误');
//                Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
//                return json_encode([
//                    'status' => -1,
//                    'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
//                ]);
//            }
//
////			  添加成功后，发送短信通知
//            if ($User && $phone) {
//                $config_id = $user->config_id;
//
//                //发送"合伙人通知"短信息通知
//                $config = SmsConfig::where('type', '12')
//                    ->where('config_id', $config_id)
//                    ->first();
//                if (!$config) {
//                    $config = SmsConfig::where('type', '12')
//                        ->where('config_id', '1234')
//                        ->first();
//                }
//                if ($config && $phone && $password) {
//                    $phone = trim($phone);
//                    $sms_data = [
//                        'Managee' => $phone,
//                        'passwordd' => $password
//                    ];
//                    $sms_result = $this->sendSms($phone, $config->app_key, $config->app_secret, $config->SignName, $config->TemplateCode, $sms_data);
//                    if ($sms_result->Code == 'OK') {
//                        Log::info('合伙人通知，'.$phone.'发送短信成功');
//                    } else {
//                        Log::info('合伙人通知，'.$phone.'发送短信失败: '.$sms_result->Message);
//                    }
//                }
//            }
//
//            return json_encode([
//                'status' => 1,
//                'message' => '下级账号添加成功',
//                'data' => $request->except(['token'])
//            ]);
//        } catch (\Exception $exception) {
//            return json_encode([
//                'status' => -1,
//                'message' => $exception->getMessage() . $exception->getFile()
//            ]);
//        }
//    }


    //代理商转移
    public function update_affiliation(Request $request)
    {
        $user_id = $request->post('userId', ''); //代理商id
        $user_pid = $request->post('userPid', ''); //转移到谁下

        $check_data = [
            'userId' => '待转代理商',
            'userPid' => '目标代理商'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $token = $this->parseToken();
        if ($token->level != '0') {
            return json_encode([
                'status' => '2',
                'message' => '非平台账号无权操作',
            ]);
        }

        $user_info = User::where('id', $user_id)
            ->where('is_delete', '0')
            ->first();
        if (!$user_info) {
            return json_encode([
                'status' => '2',
                'message' => '代理商不存在或状态异常',
            ]);
        }

        $user_pid_info = User::where('id', $user_pid)
            ->where('is_delete', '0')
            ->first();
        if (!$user_pid_info) {
            return json_encode([
                'status' => '2',
                'message' => '目标代理商不存在或状态异常',
            ]);
        }

        if ($token->user_id == $user_id) {
            return json_encode([
                'status' => '2',
                'message' => '平台账号不能被转移',
            ]);
        }

        if ($user_info->pid == $user_pid_info->id) {
            return json_encode([
                'status' => '2',
                'message' => '已是所属关系，请勿重复操作',
            ]);
        }

        $level = $user_pid_info->level + 1;

        $level_name = "业务员";
        if ($level == 1) {
            $level_name = "服务商";
        }
        if ($level == 2) {
            $level_name = "代理商";
        }

        try {
            $res = $user_info->update([
                'pid' => $user_pid_info->id,
                'level' => $level,
                'level_name' => $level_name
            ]);
            if ($res) {
                return json_encode([
                    'status' => '1',
                    'message' => '转移成功'
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => '转移失败'
                ]);
            }

        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //验证平台支付密码
    public function check_platform_pay_password(Request $request)
    {
        $rsa = new RsaE();
        try {
            $token = $this->parseToken();

            $data = $rsa->privDecrypt($request->post('sign')); //解密
            parse_str($data, $output);
            $pay_password = isset($output['pay_password']) ? $output['pay_password'] : "";
            if (strlen($pay_password) != 6) {
                return json_encode([
                    'status' => '2',
                    'message' => '密码长度不符合要求'
                ]);
            }

            $platform_pay_password = User::where('level', '0')
                ->where('pid', '0')
                ->first();
            if ($platform_pay_password && $platform_pay_password->pay_password) {
                if (Hash::check($pay_password, $platform_pay_password->pay_password)) {
                    return json_encode([
                        'status' => '1',
                        'message' => '支付密码匹配'
                    ]);
                } else {
                    return json_encode([
                        'status' => '2',
                        'message' => '支付密码不匹配'
                    ]);
                }
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => '账号未设置支付密码'
                ]);
            }
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }

    
}
